<template>
	<div class="test"></div>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	export default {
		name: 'WebsocketConnectTest',
		data() {
			return {
				wsUrl: this.$store.state.settings.wsurl, // ws地址
				websock: null, // ws实例
				islink:false
			}
		},
		// computed: {
		//   ...mapState({
		//     wsurl: state => state.settings.wsurl,
		//   }),
		// 	},
		mounted() {

			this.initWebSocket('')
		},
		destroyed() {
			// 离开路由之后断开websocket连接
			//console.log("断开websocket");
			this.websock.close()
		},
		methods: {
			// 初始化weosocket
			initWebSocket(e) {
				if(e){
					this.wsUrl = e;
				}
				console.log(this.wsUrl);
				if (typeof WebSocket === 'undefined')
					return //console.log('您的浏览器不支持websocket')
				this.websock = new WebSocket(this.wsUrl)
				this.websock.onmessage = this.websocketonmessage
				this.websock.onopen = this.websocketonopen
				this.websock.onerror = this.websocketonerror
				this.websock.onclose = this.websocketclose
				
			},
			websocketonopen() {
				//console.log("连接websocket",this.wsUrl);
				// 连接建立之后执行send方法发送数据
				//this.$message.success('连接成功');
				//console.log("发送消息")
				this.islink = true;
				let actions = { code: '0',msg:'连接成功' }
				this.websocketsend(JSON.stringify(actions))
			},
			websocketonerror() {
				// 连接建立失败重连
				//this.$message.error('连接异常');
				this.islink = false;
				this.initWebSocket()
			},
			websocketonmessage(e) {
				// 数据接收
				// const redata = JSON.parse(e)
				//console.log('接收的数据', e)
				this.$emit('websocketonmessage',e);
				const h = this.$createElement;
				// this.$notify({
				// 	title: '消息提醒',
				// 	message: h('p', {
				// 		style: 'color: teal'
				// 	}, '收到：' + e.data)
				// });
			},
			websocketsend(Data) {
				// 数据发送
				if(this.islink){
					//console.log("消息",Data)
					this.websock.send(Data)
					//this.$message.success('发送成功');
				}else{
					//this.$message.error('Socket连接异常');
				}
				
			},
			websocketclose(e) {
				// 关闭
				this.websock.close()
				//console.log('断开连接', e)
				//this.$message.error('断开连接');
			},
		},
	}
</script>

<style lang="scss" scoped>
</style>
